<template>
  <div class="login">
    <van-nav-bar title="会员登录" left-arrow @click-left="$router.go(-1)" />
    <div class="container">
      <div class="title">
        <h3>{{ loginType ? '验证码登录' : '密码登录' }}</h3>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-type">
        <div class="my-switch" :class="{ 'active': loginType }">
          <div class="my-switch-item" @click="switchToLogin">
            {{ loginType ? '使用密码登录' : '使用验证码登录' }}
          </div>
        </div>
      </div>

      <!-- 验证码登录表单 -->
      <div class="form" v-if="loginType">
        <div class="form-item">
          <input
            v-model.trim="mobile"
            class="inp"
            maxlength="11"
            placeholder="请输入手机号码"
            type="text"
            @input="validateMobile"
            @keyup.enter="focusNext('msgCode')"
          >
          <span class="error-tip" v-if="errors.mobile">{{ errors.mobile }}</span>
        </div>
        <!-- <div class="form-item">
          <input v-model.trim="picCode" class="inp" maxlength="5" placeholder="请输入图形验证码" type="text">
          <img v-if="picUrl" @click="getPicCode" :src="picUrl" alt="">
        </div> -->
        <div class="form-item">
          <input
            ref="msgCode"
            v-model.trim="msgCode"
            class="inp"
            placeholder="请输入短信验证码"
            type="text"
            @input="validateMsgCode"
            @keyup.enter="login"
          >
          <button @click="getCode" :disabled="!isMobileValid">
            {{ !timer&&second===totalSecond?'获取验证码':second+'秒后重新发送' }}
          </button>
          <span class="error-tip" v-if="errors.msgCode">{{ errors.msgCode }}</span>
        </div>
      </div>

      <!-- 密码登录表单 -->
      <div class="form" v-else>
        <div class="form-item">
          <input
            v-model.trim="mobile"
            class="inp"
            maxlength="11"
            placeholder="请输入手机号码"
            type="text"
            @input="validateMobile"
            @keyup.enter="focusNext('password')"
          >
          <span class="error-tip" v-if="errors.mobile">{{ errors.mobile }}</span>
        </div>
        <div class="form-item">
          <input
            ref="password"
            v-model.trim="password"
            class="inp"
            type="password"
            placeholder="请输入4-12位数字密码"
            @input="validatePassword"
            @keyup.enter="login"
          >
          <span class="error-tip" v-if="errors.password">{{ errors.password }}</span>
        </div>
      </div>
      <div class="login-btn" @click="login">登录</div>
      <div class="register-btn">没有账号?<span @click="$router.push('/register')">去注册</span></div>
      <div>测试账号 15119667106 <br>密码 1234 <br>验证码 {{ noteCode }}</div>
    </div>
  </div>
</template>

<script>
import { getMsgCode, codeLogin, passwordLogin } from '@/api/login'
import { Toast } from 'vant'
import { mapMutations, mapState } from 'vuex'

export default {
  name: 'LoginPage',
  // async created () {
  //   this.getPicCode()
  // },
  data () {
    return {
      loginType: false, // true为验证码登录，false为密码登录
      password: '', // 密码登录的密码
      checked: false, // 登陆方式切换
      // picCode: '', // 用户输入的图形验证码
      // picKey: '', // 将来请求传递的图形验证码唯一标识
      // picUrl: '', // 存储请求渲染的图片地址

      totalSecond: 60, // 总秒数
      second: 60, // 现秒数
      timer: null, // 倒计时 id

      mobile: '', // 存放手机号

      msgCode: '', // 用户输入的验证码
      errors: {
        mobile: '',
        password: '',
        msgCode: ''
      },
      isMobileValid: false,
      noteCode: '请先请求获取验证码'// 请求获取返回的验证码
    }
  },
  computed: {
    ...mapState('user', ['userPicCodeId'])
  },
  methods: {
    // ...mapMutations('user', ['setUserPicCodeId']),
    ...mapMutations('user', ['setUserInfo']),
    // async getPicCode () {
    //   // 携带code本地code发请求
    //   const { data: { code, base64 } } = await getPicCode(this.userPicCodeId)
    //   this.picUrl = base64
    //   this.picKey = code

    //   // 设置user仓库userPicCodeId最新值
    //   this.setUserPicCodeId(code)

    //   // Toast轻提示
    //   Toast('验证码请求成功')
    // },

    // 切换登陆方式
    switchToLogin () {
      this.loginType = !this.loginType
    },
    // 验证手机号
    validateMobile () {
      if (!this.mobile) {
        this.errors.mobile = '请输入手机号'
        this.isMobileValid = false
      } else if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
        this.errors.mobile = '请输入正确的手机号'
        this.isMobileValid = false
      } else {
        this.errors.mobile = ''
        this.isMobileValid = true
      }
    },

    // 验证密码
    validatePassword () {
      if (!this.password) {
        this.errors.password = '请输入密码'
      } else if (!/^\d{4,12}$/.test(this.password)) {
        this.errors.password = '密码必须是412位数字'
      } else {
        this.errors.password = ''
      }
    },

    // 验证短信验证码
    validateMsgCode () {
      if (!this.msgCode) {
        this.errors.msgCode = '请输入验证码'
      } else if (!/^\d{6}$/.test(this.msgCode)) {
        this.errors.msgCode = '验证码必须是6位数字'
      } else {
        this.errors.msgCode = ''
      }
    },

    // 短信验证倒计时
    async getCode () {
      if (!this.isMobileValid) {
        Toast('请输入正确的手机号')
        return
      }

      if (!this.timer && this.second === this.totalSecond) {
        // 获取短信验证码
        const { data } = await getMsgCode(this.mobile)
        if (data) {
          this.noteCode = data
          console.log('短信验证码为：', data)
        }
        Toast('发送成功，请注意查收')
        // 倒计时
        this.timer = setInterval(() => {
          this.second--
          if (this.second <= 0) {
            clearInterval(this.timer)// 清除定时器
            this.timer = null// 重置定时器
            this.second = this.totalSecond// 复位
          }
        }, 1000)
      }
    },

    // 登录
    async login () {
      // 触发所有验证
      this.validateMobile()
      if (this.loginType) {
        this.validateMsgCode()
      } else {
        this.validatePassword()
      }

      // 检查是否有错误
      if (Object.values(this.errors).some(error => error)) {
        return
      }

      try {
        let res
        if (this.loginType) {
          res = await codeLogin(this.mobile, this.msgCode)
        } else {
          res = await passwordLogin(this.mobile, this.password)
        }

        this.$store.commit('user/setUserInfo', res.data)
        Toast('登录成功')
        // 登陆成功后保存用户信息
        this.setUserInfo(res.data)
        // 登录成功后跳转首页
        const url = '/'
        this.$router.replace(url)
      } catch (error) {
        Toast('登录失败')
      }
    },

    destroyed () {
      clearInterval(this.timer)
    },

    // 添加焦点切换方法
    focusNext (refName) {
      this.$refs[refName].focus()
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 49px 29px;

  .title {
    margin-bottom: 20px;
    h3 {
      font-size: 26px;
      font-weight: normal;
    }
    p {
      line-height: 40px;
      font-size: 14px;
      color: #b8b8b8;
    }
  }

  .login-type {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .my-switch {
    width: 100%;
    height: 40px;
    background-color: #f5f5f5;
    border-radius: 50px;
    display: flex;
    justify-content: flex-start;
    transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);

    &.active {
      justify-content: flex-end;
    }

    .my-switch-item {
      width: 50%;
      height: 100%;
      background-color: #1989fa;
      color: #fff;
      border-radius: 50px;
      line-height: 40px;
      text-align: center;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }

  .form-item {
    border-bottom: 1px solid #f3f1f2;
    padding: 8px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    position: relative;
    .inp {
      display: block;
      border: none;
      outline: none;
      height: 32px;
      font-size: 14px;
      flex: 1;
    }
    img {
      width: 94px;
      height: 31px;
    }
    button {
      height: 31px;
      border: none;
      font-size: 13px;
      color: #cea26a;
      background-color: transparent;
      padding-right: 9px;
      &:disabled {
        color: #999;
      }
    }
    .error-tip {
      position: absolute;
      bottom: -18px;
      left: 8px;
      font-size: 12px;
      color: #ff4d4f;
    }
  }

  .login-btn {
    width: 100%;
    height: 42px;
    margin-top: 39px;
    background: linear-gradient(90deg,#ecb53c,#ff9211);
    color: #fff;
    border-radius: 39px;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.1);
    letter-spacing: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .register-btn {
    line-height: 42px;
    text-align: end;
    color: #999;
    span {
      color: #cea26a;
    }
  }
}

.active {
  .my-switch-item {
    background-color: rgb(25, 137, 250);
  }
}
</style>
